package com.hy.study.mapper;

import com.hy.study.bean.FlowBean;
import com.hy.study.bean.SortFlowBean;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author huyong
 * @date 2024 年 02 月 07 日 15:47: 30
 */
public class TopNMapper extends Mapper<LongWritable, Text, SortFlowBean, Text> {
    private final TreeMap<SortFlowBean, Text> resultMap = new TreeMap<>();

    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, SortFlowBean, Text>.Context context) throws IOException, InterruptedException {
        // 读取每一行 13509468723	7335	110349	117684
        String line = value.toString();
        String[] split = line.split("\t");
        String phone = split[0];
        SortFlowBean flowBean = new SortFlowBean();
        flowBean.setUpFlow(Integer.parseInt(split[1]));
        flowBean.setDownFlow(Integer.parseInt(split[2]));
        flowBean.setSumFlow(Integer.parseInt(split[3]));
        Text v = new Text();
        v.set(phone);
        resultMap.put(flowBean, v);
        // 取前10个
        if (resultMap.size() > 10) {
            // 倒序排序 将最后面的删掉
            resultMap.remove(resultMap.lastKey());
        }


    }

    @Override
    protected void cleanup(Mapper<LongWritable, Text, SortFlowBean, Text>.Context context) throws IOException, InterruptedException {
        // 这里最后写出去
        for (Map.Entry<SortFlowBean, Text> entry : resultMap.entrySet()) {
            context.write(entry.getKey(), entry.getValue());
        }

    }
}
